package com.demo.utils;


import com.demo.common.IMessageConstants;
import com.demo.ex.ServiceException;
import com.demo.security.model.SysUser;
import com.demo.security.service.UserService;
import com.demo.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 用户用聚类
 */
@Slf4j
public class UserUtil {

    /**
     * 获取当前登录用户code
     * @return
     */
    private static String getCode(){
            try {
                UserService userService = JwtTokenUtil.getUserService();
                String userCode=userService.getCurrentUserCode();
                return Optional.ofNullable(userCode).orElse("");
            }catch (Exception e){
                log.error("获取当前登录用户编码异常：", e);
                e.printStackTrace();
            }
        return "";
    }

    /**
     * 获取登录用户账号
     *
     * @return
     */
    public static String getLoginName() {
        try {
            UserService userService = JwtTokenUtil.getUserService();
            String userCode=userService.getCurrentUserCode();
            if (userCode != null ) {
                return userService.getLoginName(userCode);
            }
            return "";
        } catch (Exception e) {
            log.error(IMessageConstants.EXCEPTION_LOG, e);
            return "";
        }
    }
    /**
     * 获取登录用户
     *
     * @return
     */
    public static SysUser getSysUser() {
        UserService userService = JwtTokenUtil.getUserService();
        String userCode=userService.getCurrentUserCode();
        if (userCode != null ) {
            return userService.getUserByCode(userCode);
        }else {
            throw new ServiceException("用户未登录");
        }
    }
}
